package cn.sourcespro.spring.controller;

import cn.sourcespro.spring.crudparams.vo.Token;
import cn.sourcespro.spring.crudparams.vo.Vo;
import cn.sourcespro.spring.entity.User;
import cn.sourcespro.spring.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * security
 *
 * @author zhanghaowei
 * @date 2018/7/26
 */
@RestController
@RequestMapping("api")
public class AuthController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    @RequestMapping(value = "/auth/login", method = RequestMethod.POST)
    public Token login(String username, String password) {
        //  @RequestBody JwtAuthenticationRequest authenticationRequest
        String token = null;
        try {
            token = authService.login(username, password);
        } catch (AuthenticationException e) {
            return new Token("用户名或密码错误", HttpStatus.FORBIDDEN);
        }

        return new Token("登陆成功", token);
    }

    @RequestMapping(value = "/auth/refresh", method = RequestMethod.GET)
    public Token refreshToken(HttpServletRequest request) {
        try {
            String token = request.getHeader(tokenHeader);
            if (StringUtils.isBlank(token) || !StringUtils.contains(token, "Bearer")) {
                return new Token("参数有误", HttpStatus.BAD_REQUEST);
            }
            String refreshedToken = authService.refresh(token);
            if (refreshedToken == null) {
                return new Token("token已失效", HttpStatus.NO_CONTENT);
            } else {
                return new Token("token已刷新", refreshedToken);
            }
        } catch (Exception e) {
            return new Token("系统异常", HttpStatus.SERVICE_UNAVAILABLE);
        }
    }

    @RequestMapping(value = "${jwt.route.authentication.register}", method = RequestMethod.POST)
    public User register(@RequestBody User addedUser) throws AuthenticationException {
        return authService.register(addedUser);
    }


    @PreAuthorize("hasRole('USER')")
    @RequestMapping(value="/admin/test1")
    @ResponseBody
    public String adminTest1() {
        return "ROLE_USER";
    }

    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping("/admin/test2")
    @ResponseBody
    public String adminTest2() {
        return "ROLE_ADMIN";
    }
}
